package com.sugon.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.EnumUtil;
import com.sugon.annotation.ShiroSecurityManagerChecker;
import com.sugon.dao.DeviceInfoDao;
import com.sugon.modules.analyse.consts.KpiTarget;
import com.sugon.modules.analyse.model.vo.DeviceKpiStatParamVO;
import com.sugon.modules.kpi.model.dto.KpiDeviceDTO;
import com.sugon.modules.kpi.service.IErmsKpiManager;
import com.sugon.modules.kpi.service.IKpiTargetComputor;
import com.sugon.modules.sys.model.vo.DeviceOrganizationVO;
import com.sugon.modules.sys.service.ISysDeptManager;
import com.sugon.service.SysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 每月1号重新计算车间、产线、设备下近n年不同维度的KPI数据
 *
 * @author YuXD
 * @since 2021-03-24 17:02
 */
@Slf4j
@Component("kpiDataProcessTask")
public class KpiDataProcessTask {

    @Autowired
    private SysConfigService configService;
    @Autowired
    private ISysDeptManager deptManager;
    @Autowired
    private DeviceInfoDao deviceInfoDao;
    @Autowired
    private List<IKpiTargetComputor> kpiTargetComputors;
    @Autowired
    private IErmsKpiManager ermsKpiManager;

    /**
     * 每月1号凌晨2点
     * 重新计算近几年的KPI
     * 涉及组织：车间、产线、设备
     * 维度：七个维度
     */
    @ShiroSecurityManagerChecker
    public void doRecomputeRecentYearsKpi() {

        Integer recentYears = configService.getRecomputeKpiYears();
        // 获取今年
        int thisYear = DateUtil.thisYear();
        // 获取需要计算的设备组织树
        List<DeviceOrganizationVO> deviceOrganizationList = deptManager.loadDeviceOrganization(null);
        for (int statYear = thisYear + 1 - recentYears; statYear <= thisYear; statYear++) {
            // 清空当前年份下的所有KPI数据
            ermsKpiManager.deleteKpiDataByYearly(statYear);
            for (DeviceOrganizationVO deviceOrganization : deviceOrganizationList) {
                recompute(deviceOrganization, statYear);
            }
        }
    }

    private void recompute(DeviceOrganizationVO deviceOrganization, int yearly) {
        // 创建设备KPI统计参数并执行KPI统计
        DeviceKpiStatParamVO kpiStatParam = new DeviceKpiStatParamVO();
        kpiStatParam.setDeviceOrganizationId(deviceOrganization.getValue());
        kpiStatParam.setDeviceOrganizationCode(deviceOrganization.getCode());
        kpiStatParam.setLevel(deviceOrganization.getLevel());
        kpiStatParam.setYearly(yearly);
        doKpiCompute(kpiStatParam);
        // 如果当前设备组织下继续含有子部门，那么继续计算
        List<DeviceOrganizationVO> subOrganizationList = deviceOrganization.getChildren();
        if (CollectionUtil.isEmpty(subOrganizationList)) {
            return;
        } else {
            for (DeviceOrganizationVO subOrganizationVO : subOrganizationList) {
                recompute(subOrganizationVO, yearly);
            }
        }
    }

    public void doKpiCompute(DeviceKpiStatParamVO kpiStatParam) {
        // 如果当前设备组织下不含任何设备，那么不做后续处理
        List<KpiDeviceDTO> deviceIdLst = deviceInfoDao.listAll(kpiStatParam.getDeviceOrganizationId());
        if (CollectionUtil.isEmpty(deviceIdLst)) {
            return;
        }
        kpiStatParam.setDeviceIdLst(deviceIdLst);
        // 获取需要处理的KPI维度类别
        List<String> targetList = kpiStatParam.getTargetList();

        // 计算下统计月份
        int totalMonthly = 12;
        if (DateUtil.thisYear() == kpiStatParam.getYearly()) {
            totalMonthly = DateUtil.thisMonth();
        }

        for (String target : targetList) {
            KpiTarget kpiTarget = EnumUtil.fromString(KpiTarget.class, target);
            if (kpiTarget == null) {
                continue;
            }
            for (IKpiTargetComputor kpiTargetComputor : kpiTargetComputors) {
                if (kpiTargetComputor.getType() == kpiTarget) {
                    try {
                        List<Double> seriesData = kpiTargetComputor.compute(kpiStatParam).getSeriesData();
                        for (int i = 0; i < totalMonthly; i++) {
                            ermsKpiManager.saveKpiComputeResult(kpiStatParam.getLevel(), kpiStatParam.getDeviceOrganizationId(), target, generateMonthly(kpiStatParam.getYearly(), (i + 1)), seriesData.get(i));
                        }
                    } catch (Exception ex) {
                        // 暂不做任何处理
                        log.error(ex.getMessage(), ex);
                    }
                }
            }
        }

    }

    /**
     * 主要做月份不足10时做补0操作
     *
     * @param yealry 年份
     * @param month  月份
     * @return
     */
    private String generateMonthly(int yealry, int month) {
        return yealry + "-" + (month < 10 ? "0" : "") + month;
    }

}
